#include "stdafx.h"
#include <QEnvStatus.h>
#include <QToolsLog.h>
#include <qstatusbar.h>
#include <qdatetime.h>
#include <qplaintextedit.h>
#include <qmainwindow.h>

QStatusBar * QEnvStatus::mStatus = NULL;
QPlainTextEdit * QEnvStatus::mLogEdit = NULL;
QWidget * QEnvStatus::mInstance = NULL;
QTools::Log			QEnvStatus::mLog("env_explorer.log");

QEnvStatus::QEnvStatus(void)
{
}


QEnvStatus::~QEnvStatus(void)
{
}


QWidget * QEnvStatus::appInstance(){ return mInstance; }
QPlainTextEdit * QEnvStatus::logEdit(){ return mLogEdit; }
QStatusBar * QEnvStatus::statusBar(){ return mStatus; }

void QEnvStatus::addStatus( const String &status, int timeout, bool maskVerbose, bool log )
{
	mStatus->showMessage( TOQT(status), timeout );
	if( log ) addMessage( status, maskVerbose );
}
void QEnvStatus::addMessage( const String &status, bool maskVerbose, bool maskDebug )
{
	String msg(mLog.logMessage(status,maskVerbose, maskDebug));
	if( msg.empty() ) return;
	if( mLogEdit ){
		mLogEdit->appendPlainText(msg);
		mLogEdit->update( );
	}
}

void QEnvStatus::_register( QWidget *instance, QStatusBar * b, QPlainTextEdit * edt ){ mInstance = instance; mStatus = b; mLogEdit = edt; }


namespace QTools
{
	Log::Log( const String &name ):mName(name){
		QFile f(name);
		if( f.exists() ) f.remove();
	}
	Log::Log( ){ 
		mName = "errors.log";
		QFile f(mName);
		if( f.exists() ) f.remove();

	}
	Log::Log( const Log& log ):mName(log.mName){}

	void Log::setName( const String &name ){ 
		if( !mName.empty() ) rename( mName.cstr(), name.cstr() ); mName = name; 
	}
	const String &Log::getName() const{ return mName; }
	
	String Log::logMessage( const String &msg, bool maskVerbose, bool maskDebug )
	{
		std::ofstream strm;
		strm.open( mName.cstr(), std::ios::out|std::ios::app );

		String str(QTime::currentTime().toString("h:m:s") + ": ");
		if( maskDebug )
		{
#ifndef NDEBUG
			str += "[Debug] ";
#else
			return "";
#endif
		}
		
		if( maskVerbose )
		{
#ifdef NDEBUG
			if( QCmdLine::Instance().isVerbose() )
			{
#endif
				str +="[Verbose] ";
#ifdef NDEBUG
			}
			else return "";
#endif
		}

		if( !strm.good() ) return str;
		strm << (str+msg);
		strm.flush();
		strm.close();
		return str+msg;
	}
};